"""
设备时间管理模块 - 负责设备时间同步和时间格式处理
"""
from datetime import datetime, timedelta
from typing import Optional
from core.event_bus import event_bus, EventType
from core.config import Config

class TimeManager:
    """时间管理器"""
    
    def __init__(self, serial_manager):
        self.serial_manager = serial_manager
        self.device_start_time: Optional[datetime] = None
        self.local_start_time: Optional[datetime] = None
        self.is_synced = False
        
        # 订阅设备时间更新事件
        event_bus.subscribe(EventType.DEVICE_TIME_UPDATED, self._handle_device_time_update)
        event_bus.subscribe(EventType.DEVICE_DISCONNECTED, self._handle_device_disconnected)
    
    def _handle_device_time_update(self, time_data: dict):
        """处理设备时间更新"""
        self.device_start_time = time_data['device_time']
        self.local_start_time = time_data['local_time']
        self.is_synced = True
    
    def _handle_device_disconnected(self, reason: str):
        """处理设备断开连接"""
        self.reset_time_sync()
    
    def get_current_device_time(self) -> Optional[datetime]:
        """获取当前设备时间"""
        if not self.is_synced or not self.device_start_time or not self.local_start_time:
            return None
            
        current_local_time = datetime.now()
        time_elapsed = current_local_time - self.local_start_time
        return self.device_start_time + time_elapsed
    
    def sync_time_with_device(self) -> bool:
        """同步本地时间到设备"""
        if not self.serial_manager.is_connected:
            return False
            
        current_time = datetime.now()
        time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
        
        # 解析时间组件
        c_t = time_str.split(' ')
        c_t1 = c_t[0].split('-')
        c_t2 = c_t[1].split(':')
        
        year = int(c_t1[0]) % 100
        month = int(c_t1[1])
        week = current_time.weekday() + 1
        day = int(c_t1[2])
        hours = int(c_t2[0])
        minutes = int(c_t2[1])
        seconds = int(c_t2[2])
        
        # 转换为BCD码
        def to_bcd(value):
            tens = value // 10
            ones = value % 10
            return f"{tens:01x}{ones:01x}"
        
        time_bcd = (
            to_bcd(year) + to_bcd(month) + to_bcd(week) + to_bcd(day) +
            to_bcd(hours) + to_bcd(minutes) + to_bcd(seconds)
        )
    
        # 发送时间设置命令
        success = self.serial_manager.send_data(
            Config.CMD_TYPES['SET_TIME'], 
            value=time_bcd
        )
        
        if success:
            # 更新同步基准
            self.device_start_time = current_time
            self.local_start_time = current_time
            self.is_synced = True
            
        return success
    
    def reset_time_sync(self):
        """重置时间同步"""
        self.device_start_time = None
        self.local_start_time = None
        self.is_synced = False
    
    def is_time_synced(self) -> bool:
        """检查时间是否已同步"""
        return self.is_synced
    
    def get_time_difference(self) -> Optional[timedelta]:
        """获取设备时间与本地时间的差异"""
        device_time = self.get_current_device_time()
        if device_time is None:
            return None
            
        return device_time - datetime.now()